/**************************************************************************************
*
*	Copyright (C) 2009 - 2012 Brent Andrew O. Chua - See LICENSE.txt for more info.
*		
*	Filename	-	ThreadWorker.h
*
*	Description -	
*
*	Comments	-	
*
*	Modification History:
*			Name			   Date					Description
*			MrCodeSushi	-	08/13/2012	-	Creation of this file
**************************************************************************************/
#ifndef _PSX_THREAD_WORKER_H_
#define _PSX_THREAD_WORKER_H_

#include "PulseSTD.h"
#include "Mutex.h"
#include "Thread.h"
#include "Queue.h"

namespace Pulse
{
	class ThreadWorker 
	{
	public:

		ThreadWorker( void );

		~ThreadWorker( void );

		EErrorCode::Type Initialize( TaskScheduler *pScheduler, const CHAR *pThreadName, BOOL bInitAsThisThread = FALSE );
		
		void Join( void );

	private:

		friend void WorkerThreadMain( void *pWorkerThread );

		DWORD ThreadProc( void );

		void DoWork( TaskStatus *pToFinish = PSX_NULL );

		void Idle( void );

		void PushTask( ThreadTask *pTask );

		ThreadTask * PopTask( void );

		SIZE_T GetNumTasks( void );

		BOOL StealTasks( void );

		BOOL GiveUpSomeWork( ThreadWorker *pIdleThread );

	private:

		friend TaskScheduler;

		typedef Queue< ThreadTask * > TaskList;
		
		TaskScheduler	*m_pScheduler;
		ThreadPtr		m_pThread;

		Mutex			m_taskMutex;
		TaskList		m_tasks;

		TaskStatus *m_pCurrentTask;

	};

	PSX_INLINE SIZE_T ThreadWorker::GetNumTasks( void )
	{
		return m_tasks.GetSize();
	}
}

#endif /* _PSX_THREAD_WORKER_H_ */